﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using MessageSystem.Default.Interface;
using MessageSystem.Managed.Interface;

namespace MessageSystem.Default.implement
{
    class Connector 
    {
        public Connector(IMessageChannelFactory factory, Selector selector)
        {
            m_pFactory = factory;
            m_pSelector = selector;
            m_Processed = false;
        }

        public void Connect(string ip, UInt16 port, OnConnectSuccess os, OnConnectFailed of)
        {
            m_Success = os;
            m_Fail = of;
            IPEndPoint ipport = new IPEndPoint(IPAddress.Parse(ip), port);
            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_socket.Blocking = false;
            try
            {
                m_socket.Connect(ipport);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            
            m_pSelector.Register(m_socket);
        }

        public bool Poll()
        {
            if (m_Processed)
            {
                return true;
            }
            else
            {
                if (m_pSelector.CanWrite(m_socket))
                {
                    OnResult(true);
                }

                if (m_pSelector.IsException(m_socket))
                {
                    OnResult(false);
                }

                return false;
            }
        }

        private void OnResult(bool bSuccess)
        {
            m_Processed = true;
            if (bSuccess)
            {
                IMessageChannel client = m_pFactory.Create(m_socket);
                m_Success(client);
            }
            else
            {
                m_socket.Close();
                m_pSelector.UnRegister(m_socket);
                m_Fail();
            }
        }

        private Socket m_socket;
        private IMessageChannelFactory m_pFactory;
        private Selector m_pSelector;
        private OnConnectSuccess m_Success;
        private OnConnectFailed m_Fail;
        private bool m_Processed;
    }
}
